package com.dj.mingkong.admin.biz.repository.database.system;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dj.mingkong.admin.biz.repository.database.system.mapper.DictionaryMapper;
import com.dj.mingkong.common.enums.StatusEnum;
import com.dj.mingkong.common.infrastructure.base.dto.query.QueryVo;
import com.dj.mingkong.common.infrastructure.base.repository.BaseDatabaseRepository;
import com.dj.mingkong.common.infrastructure.eo.database.system.DictionaryEo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;


/**
 * 数据字典repository
 *
 * @author zenglonghui
 * @date: 2022/5/18 11:51
 */
@Repository
public class DictionaryRepository extends BaseDatabaseRepository<DictionaryMapper, DictionaryEo, QueryVo> {
    @Override
    protected Wrapper<DictionaryEo> buildQuery(DictionaryEo sysDictionaryEo) {
        if (sysDictionaryEo == null) {
            return null;
        }
        LambdaQueryWrapper<DictionaryEo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(sysDictionaryEo.getId() != null, DictionaryEo::getId, sysDictionaryEo);
        queryWrapper.eq(sysDictionaryEo.getParentId() != null, DictionaryEo::getParentId, sysDictionaryEo.getParentId());
        queryWrapper.likeRight(StringUtils.isNotBlank(sysDictionaryEo.getDictKey()), DictionaryEo::getDictKey, sysDictionaryEo.getDictKey());
        queryWrapper.like(StringUtils.isNotBlank(sysDictionaryEo.getDictValue()), DictionaryEo::getDictValue, sysDictionaryEo.getDictValue());
        queryWrapper.eq(sysDictionaryEo.getStatus() != null, DictionaryEo::getStatus, sysDictionaryEo.getStatus());
        queryWrapper.eq(StringUtils.isNotBlank(sysDictionaryEo.getFullKey()), DictionaryEo::getFullKey, sysDictionaryEo.getFullKey());
        queryWrapper.orderByDesc(DictionaryEo::getCreateTime);
        return queryWrapper;
    }

    public boolean existByFullKey(String fullKey) {
        return lambdaQuery().eq(DictionaryEo::getFullKey, fullKey).exists();
    }

    public Optional<DictionaryEo> oneOptByDictKey(String key) {
        return lambdaQuery()
                .eq(DictionaryEo::getDictKey, key).
                eq(DictionaryEo::getStatus, StatusEnum.VALID.getIntVal()).oneOpt();
    }

    public List<DictionaryEo> listByParentId(Long parentId) {
        return lambdaQuery()
                .eq(DictionaryEo::getParentId, parentId)
                .eq(DictionaryEo::getStatus, StatusEnum.VALID.getIntVal())
                .orderByAsc(DictionaryEo::getSort).list();
    }

    public DictionaryEo oneByFullKey(String fullKey) {
        return lambdaQuery()
                .eq(DictionaryEo::getFullKey, fullKey)
                .eq(DictionaryEo::getStatus, StatusEnum.VALID.getIntVal())
                .one();
    }
}
